/*
 * @Author: 噜噜噜 1163376226@qq.com
 * @Date: 2025-03-31 10:10:42
 * @LastEditors: 噜噜噜 1163376226@qq.com
 * @LastEditTime: 2025-04-25 15:24:55
 * @FilePath: /auto/automation-project/js/scenarioManager.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 场景管理模块
import apiConfig from "./apiConfig.js";
import Sortable from "./sortable.complete.esm.js";
let scenarios = [];
let currentScenario = null;

export function initScenarioPage() {
  loadScenarios();
  loadAllModules();

  // 初始化拖拽功能
  new Sortable(document.getElementById("selectedModules"), {
    animation: 150,
    ghostClass: "sortable-ghost",
    group: {
      name: "modules",
      pull: true,
      put: true,
    },
  });

  new Sortable(document.getElementById("allModules"), {
    animation: 150,
    ghostClass: "sortable-ghost",
    group: {
      name: "modules",
      pull: true,
      put: true,
    },
  });

  document.getElementById("newScenario").addEventListener("click", () => {
    const nameInput = document.getElementById("scenarioName");
    const scenarioName = nameInput.value.trim();
    if (!currentScenario || currentScenario.scenariosId === "") {
      // 默认场景下必须填写名称
      if (!scenarioName) {
        nameInput.focus();
        alert("请填写场景名称");
        return;
      }
      createScenario(scenarioName);
    }

    nameInput.value = "";
  });
  document
    .getElementById("scenarioList")
    .addEventListener("change", handleScenarioChange);

  document.getElementById("saveScenario").addEventListener("click", () => {
    const nameInput = document.getElementById("scenarioName");
    const scenarioName = nameInput.value.trim();

    if (!currentScenario) {
      alert("请先选择要编辑的场景");
      return;
    }

    if (!scenarioName) {
      nameInput.focus();
      alert("请输入场景名称");
      return;
    }

    // 更新当前场景名称
    currentScenario.scenariosName = scenarioName;
    saveCurrentScenario(currentScenario.scenariosId, scenarioName);

    // 清空输入框
    nameInput.value = "";
  });

  new Sortable(document.getElementById("moduleSequence"), {
    animation: 150,
    ghostClass: "sortable-ghost",
  });
}

function loadScenarios() {
  fetch(apiConfig.getURL("scenarios", "list"))
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then((data) => {
      if (data.code === 200 && data.msg) {
        scenarios = data.msg;
      } else {
        scenarios = [];
        console.warn("获取场景列表成功但数据格式不符:", data);
      }
      updateScenarioDropdown();
    })
    .catch((error) => {
      console.error("加载场景失败:", error);
      scenarios = [];
      updateScenarioDropdown();
    });
}

async function createScenario(name) {
  try {
    const moduleOrder = Array.from(
      document.querySelectorAll("#selectedModules li")
    ).map((li) => li.dataset.moduleId);
    if (moduleOrder.length === 0) {
      alert("请至少选择一个模块");
      return;
    }

    const response = await fetch(apiConfig.getURL("scenarios", "create"), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        scenariosName: name,
        moduleOrder: moduleOrder,
      }),
    });

    const result = await response.json();
    if (result.code !== 200) {
      throw new Error(result.msg || "创建场景失败");
    }

    // 创建成功后重置页面状态
    document.getElementById("scenarioName").value = "";
    document.getElementById("scenarioList").value = "";
    currentScenario = null;
    await loadAllModules();
    document.getElementById("selectedModules").innerHTML = "";
    alert(result.msg || "场景创建成功");

    return result;
  } catch (error) {
    console.error("创建场景错误:", error);
    alert("创建场景失败: " + error.message);
    throw error;
  }
}

function updateScenarioDropdown() {
  const select = document.getElementById("scenarioList");
  select.innerHTML = "";
  // 添加默认提示选项
  const defaultOption = new Option("请选择场景", "");
  defaultOption.disabled = false;
  defaultOption.selected = false;
  select.appendChild(defaultOption);

  scenarios.forEach((scenario) => {
    select.appendChild(
      new Option(scenario.scenariosName, scenario.scenariosId)
    );
  });
  // 移除之前的事件监听器
  select.removeEventListener("change", handleScenarioChange);

  // 添加新的事件监听器
  select.addEventListener("change", handleScenarioChange);

  if (currentScenario) select.value = currentScenario.id;
}

async function handleScenarioChange(e) {
  const selectedId = e.target.value;
  const selectedList = document.getElementById("selectedModules");

  if (!selectedId) {
    currentScenario = null;
    selectedList.innerHTML = ""; // 清空右侧已选模块
    await loadAllModules();
    return;
  }

  currentScenario = scenarios.find(
    (s) => String(s.scenariosId) === String(selectedId)
  );
  if (currentScenario) {
    await updateModuleSequence();
  }
}

function saveCurrentScenario(scenariosId, scenariosName) {
  // 获取当前模块顺序
  const moduleOrder = Array.from(
    document.querySelectorAll("#selectedModules li")
  ).map((li) => li.dataset.moduleId);

  fetch(apiConfig.getURL("scenarios", "update"), {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      scenariosId: scenariosId,
      scenariosName: scenariosName,
      moduleOrder: moduleOrder,
    }),
  })
    .then((response) => response.json())
    .then((result) => {
      if (result.code === 200) {
        alert(result.msg || "场景更新成功");
        // 更新成功后重新加载场景列表并重置选择
        loadScenarios();
        document.getElementById("scenarioList").value = "";
        currentScenario = null;
      } else {
        throw new Error(result.msg || "更新场景失败");
      }
    })
    .catch((error) => {
      console.error("保存场景失败:", error);
      alert("保存场景失败: " + error.message);
    });
}

// 更新模块序列 按照场景id获取场景下的模块列表，按照moduleOrder顺序显示模块
async function updateModuleSequence() {
  const selectedList = document.getElementById("selectedModules");
  const allModulesList = document.getElementById("allModules");
  selectedList.innerHTML = "";

  if (!currentScenario) return;

  try {
    // 先获取所有模块
    const allResponse = await fetch(apiConfig.getURL("modules", "list"));
    if (!allResponse.ok) throw new Error("获取模块列表失败");
    const allModules = await allResponse.json();

    // 获取当前场景的模块
    const response = await fetch(
      apiConfig.getURL("modules", "by_scenarios_id", {
        pathParams: { id: currentScenario.scenariosId },
      })
    );
    if (!response.ok) throw new Error("获取场景模块列表失败");

    const result = await response.json();
    if (result.code !== 200 || !result.modules) {
      throw new Error(result.msg || "无效的模块数据");
    }

    // 更新左侧全部模块列表，排除已选模块
    allModulesList.innerHTML = "";
    const selectedModuleIds = result.modules.map((m) => m.moduleId);

    allModules.forEach((module) => {
      if (!selectedModuleIds.includes(module.modulesId)) {
        const li = document.createElement("li");
        li.textContent = module.modulesName;
        li.dataset.moduleId = module.modulesId;
        allModulesList.appendChild(li);
      }
    });

    // 更新右侧已选模块列表
    result.modules.forEach((module) => {
      const li = document.createElement("li");
      li.textContent = module.moduleName;
      li.dataset.moduleId = module.moduleId;
      selectedList.appendChild(li);
    });
  } catch (error) {
    console.error("更新模块序列失败:", error);
  }
}

// 加载所有模块
async function loadAllModules() {
  try {
    const response = await fetch(apiConfig.getURL("modules", "list"));
    if (!response.ok) throw new Error("获取模块列表失败");

    const allModules = await response.json();
    const allModulesList = document.getElementById("allModules");
    allModulesList.innerHTML = "";

    allModules.forEach((module) => {
      const li = document.createElement("li");
      li.textContent = module.modulesName;
      li.dataset.moduleId = module.modulesId;
      allModulesList.appendChild(li);
    });
  } catch (error) {
    console.error("加载模块失败:", error);
  }
}
